const eventBus = {}
const callbacksObj = {}

eventBus.on = function (eventName, callback) {
  const callbacks = callbacksObj[eventName]
  if (callbacks) {
    callbacks.push(callback)
  } else {
    callbacksObj[eventName] = [callback]
  }
}

eventBus.emit = function (eventName, data) {
  const callbacks = callbacksObj[eventName]
  if (callbacks && callbacks.length > 0) {
    callbacks.forEach((fn) => fn(data))
  }
}

eventBus.off = function (eventName, callback) {
  if (callback) {
    const callbacks = callbacksObj[eventName]
    if (callbacks && callbacks.length > 0) {
      var index = callbacks.find((c) => c === callback)
      callbacks.splice(index, 1)
    }
  } else {
    callbacksObj[eventName] = []
  }
}

export default eventBus
